package li.teng.android.xplanet.service;



import li.teng.android.xplanet.PositionWiki;
import li.teng.android.xplanet.R;
import li.teng.android.xplanet.XplanetConstants;
import li.teng.android.xplanet.util.ApiFeatures;
import li.teng.android.xplanet.util.ApiPlatformAdapter;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.widget.Toast;

public class PositionTrackService extends Service implements LocationListener{
	
	private PreferenceManager prefManager;
	private WakeLock wakeLock;
	private NotificationManager notificationManager;
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(XplanetConstants.TAG, "TrackRecordingService.onCreate");  
		prefManager = new PreferenceManager(this);
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		registerLocationListener();
		acquireWakeLock();
		/**
		 * After 5 min, check every minute that location listener still is
		 * registered and spit out additional debugging info to the logs:
		 */
		//timer.schedule(checkLocationListener, 1000 * 60 * 5, 1000 * 60);
		showNotification();
	}
	public void acquireWakeLock() {
		try {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			if (pm == null) {
				Log.e(XplanetConstants.TAG,
						"TrackRecordingService: Power manager not found!");
				return;
			}
			if (wakeLock == null) {
				wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,XplanetConstants.TAG);
				if (wakeLock == null) {
					Log.e(XplanetConstants.TAG,
							"TrackRecordingService: Could not create wake lock (null).");
					return;
				}
			}
			if (!wakeLock.isHeld()) {
				wakeLock.acquire();
				if (!wakeLock.isHeld()) {
					Log.e(XplanetConstants.TAG,
							"TrackRecordingService: Could not acquire wake lock.");
				}
			}
		} catch (RuntimeException e) {
			Log.e(XplanetConstants.TAG,
					"TrackRecordingService: Caught unexpected exception: "
					+ e.getMessage(), e);
		}
	}
	
	public void showNotification() {
		final ApiPlatformAdapter apiPlatformAdapter =
			ApiFeatures.getInstance().getApiPlatformAdapter();
		if (true) {
			Notification notification = new Notification(
					R.drawable.icon, null /* tickerText */,
					System.currentTimeMillis());
			PendingIntent contentIntent = PendingIntent.getActivity(
					this, 0 /* requestCode */, new Intent(this, PositionWiki.class),
					0 /* flags */);
			notification.setLatestEventInfo(this, getString(R.string.app_name),
					getString(R.string.hello), contentIntent);
			notification.flags += Notification.FLAG_NO_CLEAR;
			apiPlatformAdapter.startForeground(this, notificationManager, 1,
					notification);
		} else {
			apiPlatformAdapter.stopForeground(this, notificationManager, 1);
		}
	}


	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		//if autuo voice guide is started, check if the location is in the area to start a new guide
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return binder;
	}

	private final IPositionTrackService.Stub binder =
		new IPositionTrackService.Stub() {
		@Override
		public boolean isTracking() {
			//return PostionTrackService.this.isRecording();
			return true;
		}

		@Override
		public boolean startTrack() {
			//return TrackRecordingService.this.startNewTrack();
			return true;
		}

		@Override
		public boolean stopTrack() {
			//
			return true;
		}
	};

	private SensorManager sensorManager;
	private LocationManager locationManager;
	static Location m_CurruntLocation;
	public void registerLocationListener() {
		if (locationManager == null) {
			Log.e(XplanetConstants.TAG,
					"TrackRecordingService: Do not have any location manager.");
			return;
		}
		Log.d(XplanetConstants.TAG,
		"Preparing to register location listener w/ TrackRecordingService...");
		try {
			//long desiredInterval = locationListenerPolicy.getDesiredPollingInterval();
			locationManager.requestLocationUpdates(
					XplanetConstants.GPS_PROVIDER, 1000,
					5,
					// , 0 /* minDistance, get all updates to properly time pauses */
					PositionTrackService.this);
			Log.d(XplanetConstants.TAG,
			"...location listener now registered w/ TrackRecordingService @ ");
		} catch (RuntimeException e) {
			Log.e(XplanetConstants.TAG,
					"Could not register location listener: " + e.getMessage(), e);
		}
	}


	  private final LocationListener locationListener = new LocationListener() {
		    @Override
		    public void onProviderEnabled(String provider) {
		      if (provider.equals(XplanetConstants.GPS_PROVIDER)) {

		      }
		    }

		    @Override
		    public void onProviderDisabled(String provider) {
		      if (provider.equals(XplanetConstants.GPS_PROVIDER)) {

		      }
		    }

		    @Override
		    public void onLocationChanged(Location location) {
		      if (location.getProvider().equals(XplanetConstants.GPS_PROVIDER)) {
		    	  Log.d(XplanetConstants.TAG, "PositionMap onLocationChanged");
		    	  m_CurruntLocation = location;
		      } else {

		      }
		    }

		    @Override
		    public void onStatusChanged(String provider, int status, Bundle extras) {
		      if (provider.equals(XplanetConstants.GPS_PROVIDER)) {
		        switch (status) {
		          case LocationProvider.OUT_OF_SERVICE:
		          case LocationProvider.TEMPORARILY_UNAVAILABLE:
		            break;
		        }
		      }
		    }
		  };

		  private final SensorEventListener sensorListener = new SensorEventListener() {
		    @Override
		    public void onSensorChanged(SensorEvent se) {
		      synchronized (this) {
		        float magneticHeading = se.values[0];
		      }
		    }

		    @Override
		    public void onAccuracyChanged(Sensor s, int accuracy) {
		    }
		  };
		  
		  public void alert(String txt) {
			    Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
		  }
	  
	  void registerLocationAndSensorListeners() {
		  Log.d(XplanetConstants.TAG,"registerLocationAndSensorListeners");
		    if (locationManager != null) {
		      LocationProvider gpsProvider = locationManager.getProvider(XplanetConstants.GPS_PROVIDER);
		      if (gpsProvider == null) {
		        alert(getString(R.string.missing_gps));
		        return;
		      } else {
		        Log.d(XplanetConstants.TAG, "MyTracksMap: Using location provider "
		            + gpsProvider.getName());
		      }
		      locationManager.requestLocationUpdates(gpsProvider.getName(),
		          0 /*minTime*/, 0 /*minDist*/, locationListener);
		      try {
		        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
		            1000 * 60 * 5 /*minTime*/, 0 /*minDist*/, locationListener);
		      } catch (RuntimeException e) {
		        // If anything at all goes wrong with getting a cell location do not
		        // abort. Cell location is not essential to this app.
		        Log.w(XplanetConstants.TAG,
		            "Could not register network location listener.");
		      }
		    }
		    if (sensorManager == null) {
		      return;
		    }
		    Sensor compass = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		    if (compass == null) {
		      return;
		    }
		    Log.d(XplanetConstants.TAG,"Now registering sensor listeners.");
		    sensorManager.registerListener(sensorListener, compass, SensorManager.SENSOR_DELAY_UI);
		  }
	  
	  void unregisterLocationAndSensorListeners() {
		    if (locationManager != null) {
		      locationManager.removeUpdates(locationListener);
		    }
		    if (sensorManager != null) {
		      sensorManager.unregisterListener(sensorListener);
		    }
		  }

}
